<?php

namespace frontend\modules\dynamic\models;

use Yii;
use yii\base\Model;
use yii\db\Exception;
use yii\web\HttpException;
use common\models\dynamic\Dynamic;
use common\models\dynamic\DynamicVideo;
use common\exceptions\ModelHttpException;

class DynamicVideoForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $retweet_id
     * @var integer 转发动态ID
     */
    public $retweet_id = 0;

    /**
     * @name $content
     * @var string 动态内容
     */
    public $content = '';

    /**
     * @name $video
     * @var integer 视频地址
     */
    public $filename;

    /**
     * @name $duration
     * @var int 视频时长 （s）
     */
    public $duration;

    /**
     * @name $position
     * @var string 位置
     */
    public $position = '';

    /**
     * @format 格式
     * @var int
     */
    public $format = Dynamic::FORMAT_VIDEO;

    /**
     * @name $attachs
     * @var \common\models\Attachment 附件集合
     */
    private $attachs = null;

    public function rules() {
        return [
            [['user_id', 'retweet_id', 'duration'], 'integer'],
            [['filename'], 'string', 'max' => 120],
            [['position'], 'string', 'max' => 60],
            [['filename', 'duration'], 'required'],
        ];
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            throw new ModelHttpException('发布提交失败', $this->getFirstErrors());
        }

        $model = new Dynamic();
        $model->attributes = [
            'user_id' => $this->user_id,
            'position' => $this->position,
            'retweet_id' => $this->retweet_id,
            'format' => $this->format,
            'content' => $this->content
        ];

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new ModelHttpException('动态内容保存时失败', $model->getFirstErrors());
            }

            $video = new DynamicVideo();
            $video->attributes = [
                'user_id' => $this->user_id,
                'dynamic_id' => $model->id,
                'path' => $this->filename,
                'duration' => $this->duration,
                'video_id' => 0
            ];

            if (!$video->save()) {
                throw new Exception('视频保存失败！');
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            throw new HttpException(418, $e->getMessage());
        }

        // 正则匹配 @ 人员 搜索
//        $this->pushAtMesaage($this->content, $model->id);
        // 话题匹配
//        $this->matchTopic($this->content, $model->id);

        return array_merge($model->attributes, [
            'filename' => $video->path,
            'duration' => $video->duration,
            'format' => '视频动态'
        ]);
        ;
    }

    /**
     * 推送 @ at 消息
     *
     * @return void
     */
    protected function pushAtMesaage($content, $dynamicId) {
        // 正则匹配 @ 人员 搜索
        $array = [];
        $users = [];
        if (preg_match_all("/\@([\x{4e00}-\x{9fa5}'a-z'A-Z'0-9'_'-]+)/u", $content, $array)) {
            if (count($array) > 1) {
                $users = $array[1];
                // 获取到被at 用户 走入推送 消息队列
                foreach ($users as $username) {
                    
                }
            }
        }
    }

    /**
     * 从动态内容 匹配包含的话题
     *
     * @param [type] $content
     * @return void
     */
    protected function matchTopic($content, $dynamicId) {
        $tagsarr = [];
        // 话题匹配
        $tag_pattern = "/\#([^\#|.]+)\#/";
        if (preg_match_all($tag_pattern, $content, $tagsarr)) {
            if (count($tagsarr) > 1) {
                $topics = $tagsarr[1];
                foreach ($topics as $topic) {
                    
                }
            }
        }
    }

}
